跳到主要内容

124 二叉树中的最大路径和

https://leetcode.cn/leetbook/read/top-interview-questions-hard/xdhfe5/

cost: 33m57s

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root) {
int sum = INT_MIN / 10;
this->maxPathSum_(root, sum);
return this->res;
}

private:
int maxPathSum_(TreeNode* root, int sum) {
if (root == nullptr) {
return INT_MIN / 10;
}
int v1 = this->maxPathSum_(root->left, sum + root->val);
int v2 = this->maxPathSum_(root->right, sum + root->val);
if (v1 < v2) {
std::swap(v1, v2);
}
int maxChildSum = std::max(v1 + root->val, v2 + root->val);
maxChildSum = std::max(maxChildSum, root->val);
res = std::max(res, maxChildSum);
res = std::max(res, sum);
res = std::max(res, v1 + v2 + root->val);
res = std::max(res, v1 + sum + root->val);
res = std::max(res, sum + root->val);
return maxChildSum;
}
int res = INT_MIN / 10;
};